/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BALoginViewController.m
//  redia-bapps-ios
//
//  Created by Henrik Lynbech on 12/08/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BALoginViewController.h"
#import "BAUtils.h"
#import "BARPCManager.h"
#import "BAPatronSettings.h"
#import "BARootViewController.h"
#import "BALibrarySettings.h"
#import "BASettingsUserDefaultsKeys.h"
#import "BACPRPolicyPopup.h"
#import "BAFlyoutMenuViewController.h"
#import "UIImage+MultiplyColor.h"
#import "LazyLoadManager.h"
#import "BAErrorCodes.h"
#import "InfoGalleriImageUrlUtils.h"

@interface BALoginViewController () {
    BACPRPolicyPopup* cprPopupManager;
}

@property (assign, nonatomic) BOOL isAttemptingLogin;
@property (assign, nonatomic) BOOL checkForUserRoleSwitching;
@property (assign, nonatomic) BOOL reLoginPreviousLibrarianAccessAllowed;
@property (assign, nonatomic) BOOL reLoginPreviousIMFEditorAccessAllowed;

@end

@implementation BALoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [((BACustomNavigationBar*)self.navigationController.navigationBar) changeToTopOnlyCustomerColorAnimated:NO];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.isAttemptingLogin = NO;
    
    RD_SET_EDGES_FOR_EXTENDED_LAYOUT_IOS7
    BA_FLYOUT_MENU_ADD_BUTTON(BASpecialNavigationBarConfigurationDefault)
    BA_LABEL_SET_FONT_LIGHT(self.userNameTextField);
    BA_LABEL_SET_FONT_LIGHT(self.passswordTextField);
    
    BA_LABEL_SET_FONT_REGULAR(self.rememberLoginLabel);
    self.rememberLoginLabel.textColor = [UIColor colorWithWhite:48.0/255.0 alpha:1];
    
    BA_LABEL_SET_FONT_REGULAR(self.loginButton.titleLabel);
    BA_BUTTON_ADD_PRESSED_STATE_OVERLAY(self.loginButton);
    BA_LABEL_SET_FONT_REGULAR(self.cancelButton.titleLabel);
    BA_BUTTON_ADD_PRESSED_STATE_OVERLAY(self.cancelButton);
    
    BA_LABEL_SET_FONT_LIGHT(self.detailsLabel);
    self.detailsLabel.contentMode = UIViewContentModeBottom;
    
    self.userNameTextField.layer.cornerRadius = 0;
    self.passswordTextField.layer.cornerRadius = 0;

    self.rememberLoginButton.layer.borderColor = [UIColor colorWithWhite:0.40 alpha:1].CGColor;
    self.rememberLoginButton.layer.cornerRadius = 0;
    
    if (RD_IS_RETINA_SCREEN) {
        self.userNameTextField.layer.borderWidth = 0.5;
        self.passswordTextField.layer.borderWidth = 0.5;
        self.rememberLoginButton.layer.borderWidth = 0.5;
    } else {
        self.userNameTextField.layer.borderColor = [UIColor colorWithWhite:0.5 alpha:1].CGColor;
        self.passswordTextField.layer.borderColor = [UIColor colorWithWhite:0.5 alpha:1].CGColor;
        self.rememberLoginButton.layer.borderColor = [UIColor colorWithWhite:0.5 alpha:1].CGColor;
    }
    
    UITapGestureRecognizer* gest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(someWhereElseClicked:)];
    gest.cancelsTouchesInView=NO;
    [self.view addGestureRecognizer:gest];
    
#if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_7_1
#error Following code not working for iPhone 6 and forward
#else
    if (RD_IS_IPHONE && !(RD_IS_IPHONE5)) {
        self.headerImageView.contentMode = UIViewContentModeScaleAspectFit;
        self.headerViewHeightConstraint.constant = 50;
    }
#endif
    
    NSString* logo_url = [[BALibrarySettings instance] getLogoUrlStringForType:BALibrarySettingsLogoUrlTypeLogin];
    if (logo_url!=nil && [logo_url length]>0) {
        
        self.headerImageView.image = nil; //display nothing while loading
        
        bool isIPad = RD_IS_IPAD;
        
        NSString* resizeUrl = [InfoGalleriImageUrlUtils getResizedImageUrl:logo_url
                                                                   toWidth:isIPad ? 320 : 282
                                                                  toHeight:isIPad ? 106 : 94
                                                              usingQuality:9
                                                                  withMode:IMAGE_URL_UTILS_RESIZE_MODE_BOUNDING_BOX
                                                              outputFormat:@"png"
                                                         doubleUpForRetina:YES];
        
        [[LazyLoadManager instance] lazyLoadUIImageFromUrl:resizeUrl
                                         setScaleforRetina:YES
                                                 onSuccess:^(UIImage *image) {
                                                     self.headerImageView.image = image;
                                                 }
                                                   onError:^(LazyLoaderErrorCode errorCode, NSString *errorMessage) {
                                                       self.headerImageView.image = nil;
                                                   }
         ];
    } else {
        self.headerImageView.image=nil;
    }
    
    
    if ([[BAPatronSettings instance] persistLoginInfo]) {
        [self.userNameTextField setText:[[BAPatronSettings instance] persistedUserName]];
        [self.passswordTextField setText:[[BAPatronSettings instance] persistedPassword]];
        UIColor *checkmarkColor = [[BALibrarySettings instance] getCustomerColorNormal];
        if (checkmarkColor == nil) {
            checkmarkColor = [UIColor blackColor];
        }
        [self.rememberLoginButton setImage:[UIImage imageNamed:@"login-checkmark" multiplyWithColor:checkmarkColor] forState:UIControlStateNormal];
    }
    else {
        if ([[BAPatronSettings instance] hasPerformedSuccessfullLogin]) {
            self.userNameTextField.text = [[BAPatronSettings instance] loggedInUserName];
        }
        
#ifdef DEBUG
        // HACK: INSERT DEFAULT TEST USER CREDENTIALS
        BA_BAPPS_SETUP_DEBUG_AND_TEST_CREDENTIALS
#endif
    }

    // Populate the header view according to the state that we are in.
    if (self.successBlock) {
        if ([[BAPatronSettings instance] hasPerformedSuccessfullLogin]) {
            // Re-login attempt.
            self.detailsLabel.text = @"Dit login er udløbet. Log venligst ind igen for at bruge den valgte funktion.";
        }
        else {
            self.detailsLabel.text = @"For at bruge denne funktion skal du logge ind.";
        }
    }
    
//    self.librarianLoginTest.hidden = ![[BALibrarySettings instance] isLibrarianModeAllowed];

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self enableUserInteraction];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSUInteger)supportedInterfaceOrientations{
    if (RD_IS_IPAD) {
        return UIInterfaceOrientationMaskLandscape;
    } else{
        return UIInterfaceOrientationMaskPortrait;
    }
}

-(void)someWhereElseClicked:(id)sender
{
    [self.userNameTextField resignFirstResponder];
    [self.passswordTextField resignFirstResponder];
}

- (void)enterAttemptingLoginState
{
    self.navigationController.navigationBar.userInteractionEnabled = NO;
    self.isAttemptingLogin = YES;
    self.userNameTextField.enabled = NO;
    self.passswordTextField.enabled = NO;
    self.loginButton.enabled = NO;
    self.loginButton.alpha = 0.5;
    self.rememberLoginButton.enabled = NO;
    [self.cancelButton setTitle:@"AFBRYD" forState:UIControlStateNormal];
    [self.attemptingLoginIndicator startAnimating];
}

- (void)exitAttemptingLoginState
{
    self.navigationController.navigationBar.userInteractionEnabled = YES;
    self.isAttemptingLogin = NO;
    self.userNameTextField.enabled = YES;
    self.passswordTextField.enabled = YES;
    self.loginButton.enabled = YES;
    self.loginButton.alpha = 1.0;
    self.rememberLoginButton.enabled = YES;
    [self.cancelButton setTitle:@"ANNULLER" forState:UIControlStateNormal];
    [self.attemptingLoginIndicator stopAnimating];
}

- (IBAction)loginClicked:(id)sender {
    if ([self.userNameTextField.text length]==0) {
        UIAlertView* v = [[UIAlertView alloc] initWithTitle:@"Manglende brugernavn" message:@"Du kan ikke logge ind uden at indtaste dit lånernummer." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [v show];
        return;
    }
    if ([self.passswordTextField.text length]==0) {
        UIAlertView* v = [[UIAlertView alloc] initWithTitle:@"Manglende pinkode" message:@"Du kan ikke logge ind uden at indtaste din pinkode." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [v show];
        return;

    }
    
    // Check that the user has accepted the privacy policy.
    if ([BALibrarySettings instance].isImfEnabled && [[BAPatronSettings instance] hasUserAcceptedPolicy:self.userNameTextField.text] == NO) {
        // Present the privacy policy view.
        cprPopupManager = [BACPRPolicyPopup new];
        cprPopupManager.delegate = self;
        [cprPopupManager showPopup];
    }
    else {
     
        [self authenticate];
    }
}

- (void)userAnsweredCPRPolicy:(BOOL)answer
{
    if (answer == YES) {
        // The user accepted the CPR policy - commence logging in.
        [[BAPatronSettings instance] addUserToAcceptedUsers:self.userNameTextField.text];
        [self authenticate];
    }
    else {
        /* removed: don't annoy the user
        self.userNameTextField.text = @"";
        self.passswordTextField.text = @"";
        [[BAPatronSettings instance] clearPersistedCredentials];
        [[BAPatronSettings instance] setPersistLoginInfo:NO];
        [self.rememberLoginButton setImage:nil forState:UIControlStateNormal];
        */
        UIAlertView* v = [[UIAlertView alloc] initWithTitle:@"Advarsel" message:@"Hvis du ikke accepterer app'ens brug af dit lånerkortnummer, kan du ikke se og forny lån eller reservere bøger." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [v show];
    }
    cprPopupManager=nil;
}

- (void)authenticate
{
    [self enterAttemptingLoginState];
    NSString* username = self.userNameTextField.text;
    NSString* password = self.passswordTextField.text;
    [BARPCManager authenticateAsyncFromView:self
                                   username:username
                                   password:password
                                resultBlock:^(BAPatron *result) {
                                    
                                    [BAPatronSettings instance].patronObject = result;
                                    [BAPatronSettings instance].loggedInUserName = username;
                                    [BAPatronSettings instance].hasPerformedSuccessfullLogin = YES;
                                    // Persist user info upon successful login.
                                    if ([[BAPatronSettings instance] persistLoginInfo]) {
                                        [[BAPatronSettings instance] setPersistedCredentialsForUser:username password:password];
                                    }
                                    
                                    if (self.checkForUserRoleSwitching) {
                                        //check if credentials roles have changed during relogin
                                        if (self.reLoginPreviousLibrarianAccessAllowed != [[BAPatronSettings instance] isUserAllowedLibrarianAccessForCurrentLibrary] || self.reLoginPreviousIMFEditorAccessAllowed != [[BAPatronSettings instance] isUserAllowedIMFEditorAccessForCurrentLibrary]) {
                                            //user credentials role changed, so discard complete tab bar and all views and don't callback
                                            [[BARootViewController instance] switchToMainTabBarAppMode];
                                            
                                        } else {
                                            if (self.successBlock) {
                                                self.successBlock();
                                                [self dismissViewControllerAnimated:YES completion:NULL];
                                            }
                                        }
                                    }
                                    else {
                                        [[BARootViewController instance] switchToMainTabBarAppMode];
                                    }
                                    [self exitAttemptingLoginState];
                                }
                                 errorBlock:^(int errorCode, NSString *errorMessage) {
                                     [BAPatronSettings instance].loggedInUserName=@"";
                                     
                                     if (self.checkForUserRoleSwitching) {
                                         //check if special credentials were invoked before relogin failed
                                         if (self.reLoginPreviousIMFEditorAccessAllowed || self.reLoginPreviousLibrarianAccessAllowed) {
                                             //user credentials role changed, so discard complete tab bar and all views and don't callback
                                             [[BARootViewController instance] switchToMainTabBarAppMode];
                                             
                                         } else {
                                             if (self.errorBlock) {
                                                 self.errorBlock(errorCode, errorMessage);
                                                 [self dismissViewControllerAnimated:YES completion:NULL];
                                             }
                                         }
                                     }
                                     else {
                                         UIAlertView* v = [[UIAlertView alloc] initWithTitle:@"Kunne ikke logge ind" message:errorMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                                         [v show];
                                     }
                                     [self exitAttemptingLoginState];
                                 }];
}

- (IBAction)rememberLoginClicked:(id)sender
{
    if ([[BAPatronSettings instance] persistLoginInfo]) {
        // Disable storing of login info and remove any information already stored.
        [[BAPatronSettings instance] clearPersistedCredentials];
        [[BAPatronSettings instance] setPersistLoginInfo:NO];
        [self.rememberLoginButton setImage:nil forState:UIControlStateNormal];
    }
    else {
        [[BAPatronSettings instance] setPersistLoginInfo:YES];
        UIColor *checkmarkColor = [[BALibrarySettings instance] getCustomerColorNormal];
        if (checkmarkColor == nil) {
            checkmarkColor = [UIColor blackColor];
        }
        [self.rememberLoginButton setImage:[UIImage imageNamed:@"login-checkmark" multiplyWithColor:checkmarkColor] forState:UIControlStateNormal];
    }
}

- (IBAction)cancelButtonClicked:(id)sender
{
    if (self.isAttemptingLogin) {
        // Cancel the login attempt.
        [BARPCManager closeConnectionsForView:self];
        [self exitAttemptingLoginState];
    }
    else {
        [BAPatronSettings instance].patronObject = nil;
        if (self.checkForUserRoleSwitching) {
            //check if special credentials were invoked before relogin failed
            if (self.reLoginPreviousIMFEditorAccessAllowed || self.reLoginPreviousLibrarianAccessAllowed) {
                //user credentials role changed, so discard complete tab bar and all views and don't callback
                [[BARootViewController instance] switchToMainTabBarAppMode];
                
            } else {
                if (self.errorBlock) {
                    self.errorBlock(BA_ERROR_LOGIN_USER_REJECTED, @"Brugeren afbrød login-forsøget");
                    [self dismissViewControllerAnimated:YES completion:NULL];
                }
            }
        }
        else {
            // This comes from the main login dialog - go directly to the main app without modifying patron info
            [[BARootViewController instance] switchToMainTabBarAppMode];
        }
    }
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.userNameTextField) {
        [self.userNameTextField resignFirstResponder];
        [self.passswordTextField becomeFirstResponder];
    } else {
        [self loginClicked:textField];
    }
    return YES;
}

//- (IBAction)librarianLoginTestClicked:(id)sender {
//    if (![[BALibrarySettings instance] isLibrarianModeAllowed]) {
//        UIAlertView* v = [[UIAlertView alloc] initWithTitle:@"Blokeret" message:@"Bibliotekar-tilstand ikke tilgængelig for det valgte bibliotek." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//        [v show];
//    } else {
//        [[BALibrarySettings instance] setIsCurrentlyInLibrarianMode:YES];
//        [self loginClicked:sender];
//    }
//}


#pragma mark - Flyout menu

BA_FLYOUT_MENU_ADD_CALLBACK

- (void)enableUserInteraction
{
    self.view.userInteractionEnabled = YES;
}

- (void)disableUserInteraction
{
    self.view.userInteractionEnabled = NO;
}

+ (void)checkLoginStatusFromViewController:(UIViewController *)viewController
                               resultBlock:(BALoginSuccessBlock)successBlock
                                errorBlock:(BALoginErrorBlock)failureBlock;
{
    if ([BARPCManager isStillAuthenticated]) {
        // No need to refresh the session.
        if (successBlock) {
            successBlock();
        }
    }
    else {
        // We need to refresh the session.
        // First we check whether the user has already stored the login information.
        if ([[BAPatronSettings instance] persistLoginInfo] &&
            [[[BAPatronSettings instance] persistedUserName] length] > 0 &&
            [[[BAPatronSettings instance] persistedPassword] length] > 0) {
            [BARPCManager authenticateAsyncFromView:viewController
                                           username:[[BAPatronSettings instance] persistedUserName]
                                           password:[[BAPatronSettings instance] persistedPassword]
                                        resultBlock:^(BAPatron *result) {
                                            
                                            bool reLoginPreviousIMFEditorAccessAllowed = [[BAPatronSettings instance] isUserAllowedIMFEditorAccessForCurrentLibrary];
                                            bool reLoginPreviousLibrarianAccessAllowed = [[BAPatronSettings instance] isUserAllowedLibrarianAccessForCurrentLibrary];

                                            [BAPatronSettings instance].patronObject = result;
                                            
                                            if (reLoginPreviousLibrarianAccessAllowed != [[BAPatronSettings instance] isUserAllowedLibrarianAccessForCurrentLibrary] || reLoginPreviousIMFEditorAccessAllowed != [[BAPatronSettings instance] isUserAllowedIMFEditorAccessForCurrentLibrary]) {
                                                //user credentials role changed, so discard complete tab bar and all views and don't callback
                                                [BAPatronSettings instance].patronObject = nil;
                                                if (failureBlock) {
                                                    failureBlock(BA_ERROR_USER_ROLE_SWITCHING_DISALLOWED, @"Kunne ikke udføre funktionen fordi det gemte login er med en anden adgangstilladelse. Fjern det gemte login og prøv igen.");
                                                }
                                            } else {
                                                if (successBlock) {
                                                    successBlock();
                                                }
                                            }
                                        }
                                         errorBlock:^(int errorCode, NSString *errorMessage) {
                                             UIAlertView* v = [[UIAlertView alloc] initWithTitle:@"Kunne ikke logge ind" message:errorMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                                             [v show];
                                             [BAPatronSettings instance].patronObject = nil;
                                             if (failureBlock) {
                                                 failureBlock(errorCode, errorMessage);
                                             }
                                         }];
        }
        else {
            // We need to display a login dialog.
            BALoginViewController *loginVC = [[BALoginViewController alloc] initWithNibName:@"BALoginViewController" bundle:nil];
            loginVC.checkForUserRoleSwitching = YES;
            loginVC.successBlock = successBlock;
            loginVC.errorBlock = failureBlock;
            loginVC.reLoginPreviousIMFEditorAccessAllowed = [[BAPatronSettings instance] isUserAllowedIMFEditorAccessForCurrentLibrary];
            loginVC.reLoginPreviousLibrarianAccessAllowed = [[BAPatronSettings instance] isUserAllowedLibrarianAccessForCurrentLibrary];
            
            [viewController presentViewController:loginVC animated:YES completion:NULL];
        }
    }
}


@end
